package com.gitee.luosl.cola.match.pattern;

import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Created by luosl on 2021/03/30/9:46
 */
abstract public class Pattern1<T, R> implements Pattern<T, R> {

    public static <T> Pattern1<T, T> create(Predicate<T> predicate) {
        return new Pattern1<T, T>() {

            @Override
            public T apply(T value) {
                return value;
            }

            @Override
            public boolean isDefinedAt(T value) {
                return predicate.test(value);
            }
        };
    }

    public static <T, R, R1> Pattern1<T, R1> of(Class<? super T> clazz, Predicate<T> predicate, Pattern<R, R1> pattern, Function<T, R> unapply){
        return new Pattern1<T, R1>() {
            @Override
            public R1 apply(T value) {
                return pattern.apply(unapply.apply(value));
            }

            @Override
            public boolean isDefinedAt(T value) {
                return clazz.isInstance(value)
                        && predicate.test(value)
                        && pattern.isDefinedAt(unapply.apply(value));
            }
        };
    }
}
